import axios from 'axios'
import {ElMessage, ElLoading } from 'element-plus'
import router from '../router/index.js'

let loading

function startLoading() {
    loading = ElLoading.service({
        lock: true,
        text: '加载中....',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() {
    loading.close()
}

const request = axios.create({
    timeout: 5000
})

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
    startLoading()
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    // config.headers['token'] = user.token;  // 设置请求头
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        endLoading()
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        ElMessage.error("操作失败，服务器响应异常")
        console.log(error.response.data)
        endLoading()

        // 获取状态码
        let status  = error.response

        if (status === 404) {
            ElMessage.error('404')
            //清除token
            localStorage.removeItem('eToken')
            //跳转到登录页面
            router.push('/404')
        }
        return Promise.reject(error)
    }
)

// 封装get方法
function get(url, params){
    return new Promise((resolve, reject) =>{
        axios.get(url, params).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

// 封装post方法
function post(url, params){
    return new Promise((resolve, reject) =>{
        axios.post(url, params).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

// 封装update方法
function update(url, params){
    return new Promise((resolve, reject) =>{
        axios.put(url, params).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

// 封装delete方法
function delete1(url, params){
    return new Promise((resolve, reject) =>{
        axios.delete(url, params).then(res =>{
            resolve(res.data);
        }).catch(err =>{
            reject(err.data);
        })
    });
}

//对外接口
export function request1({method, url, data}){
    startLoading()
    switch (method){
        case "get":
            endLoading()
            return get(url, data);
            break
        case "post":
            endLoading()
            return post(url, data);
            break
        case "update":
            endLoading()
            return update(url, data);
            break
        case "delete":
            endLoading()
            return delete1(url, data);
            break
    }
}

export default request